import { PageModalService } from 'src/app/shared/service/page-modal-service';
import { Component, OnInit, Input, Output, EventEmitter, OnChanges, SimpleChanges, ChangeDetectorRef } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

import { Camera, CameraOptions } from '@ionic-native/camera/ngx';
import { VideoCapturePlus, VideoCapturePlusOptions, MediaFile } from '@ionic-native/video-capture-plus/ngx';
import { File, FileEntry } from '@ionic-native/file/ngx';

import { ActionSheetController } from '@ionic/angular';
import { ModalController, NavParams, Platform, LoadingController } from '@ionic/angular';

import { HttpService } from 'src/app/shared/service/http.service';
import { AppGlobalService } from 'src/app/shared/service/app-global.service';

import { ImgPage } from '../../upload-image/img.page';
import { UploadImageComponent } from './../../upload-image/upload-image.component';
import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer/ngx';
import { FilePath } from '@ionic-native/file-path/ngx';
import { Chooser } from '@ionic-native/chooser/ngx';


import { VideoEditor } from '@ionic-native/video-editor/ngx';
import { UploadImageService } from 'src/app/shared/service/uploadImageService';
import { CustomPopoverComponent } from '../../custom-popover/custom-popover.component';
declare var MediaPicker;
@Component({
  selector: 'app-photo-select',
  templateUrl: './photo-select.component.html',
  styleUrls: ['./photo-select.component.scss'],
})
export class PhotoSelectComponent implements OnInit {
  @Input() tagData: any;
  @Output() updateUrl: EventEmitter<any> = new EventEmitter();
  orgPath: any;
  isNative: boolean;
  maxSize = 8;
  minSize = 0;
  forPdf = false;
  forTextInput = false;
  // 上传图片
  selectImg: any;
  loaderToShow: any;
  imageResponse: any;
  isCompleteBatchUpload = 0;
  currentTime: any;

  compressionProgress = 0;
  uploadProgress = 0;
  uploadFileModalId = 'FileUploadPopoverModal';
  isAbortUpload = false; // 2024.11.11
  fileTransfer: FileTransferObject;
  constructor(
    private appGlobalService: AppGlobalService,
    private modalCtrl: ModalController,
    private camera: Camera,
    private http: HttpService,
    private platform: Platform,
    private ref: ChangeDetectorRef,
    private actionSheetCtrl: ActionSheetController,
    private loadingController: LoadingController,
    private sanitizer: DomSanitizer,
    private videoCapturePlus: VideoCapturePlus,
    private transfer: FileTransfer,
    private chooser: Chooser,
    private videoEditor: VideoEditor,
    private pageModalService: PageModalService,
    private uploadImageService: UploadImageService,
    private modalContrl: ModalController

  ) { }



  // 2024.11.01 上传文件回传值
  async showFileUploadPopover(type, tagData) {
    const modal = await this.modalContrl.create({
      showBackdrop: true,
      cssClass: 'custom-popover',
      backdropDismiss: false,
      id: this.uploadFileModalId,
      component: CustomPopoverComponent,
      componentProps: { tagData, type }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss().then((data) => {
      console.log(data, "showPopover dimiss");
    }); // 获取关闭传回的值
  }

  ngOnInit() {




    this.tagData.valueArray = [];
    if (!this.tagData.extra && this.tagData.formType === 'addReleasePhoto') {
      this.tagData.extra = '添加图片';
    }
    if (this.tagData.textType && this.tagData.textType === 'pdf') {
      this.forPdf = true;
    }
    if (this.tagData.textType && this.tagData.textType === 'textInput') {
      this.forTextInput = true;
      this.tagData.valueIndexArray = this.tagData.valueIndex ? this.tagData.valueIndex.split(";") : [];
    }
    if (this.tagData.formType === 'fileSelectWidget') {
      this.tagData.valueArray = this.tagData.value ? this.tagData.value.split(";") : [];
      this.tagData.valueIndexArray = this.tagData.valueN ? this.tagData.valueN.split(";") : [];
      this.tagData.valueLongArray = [];
      if (this.tagData.valueArray.length > 0) {
        this.tagData.valueArray.forEach(element => {
          this.tagData.valueLongArray.push(element.split('.').pop());
        });
      }

      this.maxSize = Number(this.tagData.maxSize ? this.tagData.maxSize : 10);
    }
    this.currentTime = 'time' + Date.now();
    if (this.platform.is('cordova')) {
      this.isNative = true;
    } else {
      this.isNative = false;
    }
    if (this.tagData.formType === 'photoVideoSelectWidget' && this.tagData.subHtmlObj && this.tagData.subHtmlObj.length > 2) {

      this.maxSize = Number(this.tagData.subHtmlObj[0].maxSize ? this.tagData.subHtmlObj[0].maxSize : 8);
      this.minSize = Number(this.tagData.subHtmlObj[0].minSize ? this.tagData.subHtmlObj[0].minSize : 0);
      if (this.tagData.subHtmlObj[0].value && this.tagData.subHtmlObj[0].value.indexOf(';') > -1) {
        const urlArray = this.tagData.subHtmlObj[0].value.split(';');
        urlArray.forEach(element => {
          this.tagData.valueArray.push({ path: element });
        });
      } else if (this.tagData.subHtmlObj[0].value && this.tagData.subHtmlObj[0].value.length > 1) {
        this.tagData.valueArray.push({ path: this.tagData.subHtmlObj[0].value });
      }

    } else {
      this.maxSize = Number(this.tagData.maxSize ? this.tagData.maxSize : 8);
      // pdf
      if (this.forPdf) {
        // 首图
        this.tagData.valueIndexArray = this.getValueArrayFromValueStr(this.tagData.valueIndex);
        // 长图
        this.tagData.valueLongArray = this.getValueArrayFromValueStr(this.tagData.valueLong);

      }
      // 正常图片或者pdf值
      this.tagData.valueArray = this.getValueArrayFromValueStr(this.tagData.value);

    }
    setTimeout(() => {
      this.updateTagData();
    }, 1000);

  }

  getValueArrayFromValueStr(valueString) {
    const valueArray = [];
    if (valueString && valueString.indexOf(';') > -1) {
      const urlArray = valueString.split(';');
      urlArray.forEach(element => {
        valueArray.push({ path: element });
      });
    } else if (valueString && valueString.length > 1) {
      valueArray.push({ path: valueString });
    }
    return valueArray;
  }
  getValueStrFromArray(valueArray) {
    let urlStr = '';
    if (valueArray && valueArray.length > 0) {
      const array = [];
      valueArray.forEach(element => {
        array.push(element.path);
      });
      urlStr = array.join(';');
    }
    return urlStr;
  }

  updateTagData() {
    const urlStr = this.getValueStrFromArray(this.tagData.valueArray);
    if (this.tagData.formType === 'photoVideoSelectWidget') {
      this.tagData.subHtmlObj[0].value = urlStr;
    } else {
      this.tagData.value = urlStr;
    }

    // pdf
    if (this.forPdf) {
      const valueIndexStr = this.getValueStrFromArray(this.tagData.valueIndexArray);
      this.tagData.valueIndex = valueIndexStr;
      const valueLongStr = this.getValueStrFromArray(this.tagData.valueLongArray);
      this.tagData.valueLong = valueLongStr;
    }
    if (this.forTextInput) {
      const valueIndexArray: any = [];
      for (let index = 0; index < this.tagData.valueArray.length; index++) {
        const value = document.getElementById(this.tagData.formKey + "_" + index) as HTMLInputElement;
        if (value) {
          valueIndexArray.push(value.value ? value.value : "");
        } else {
          valueIndexArray.push("");
        }
      }
      this.tagData.valueIndexArray = valueIndexArray;
      this.tagData.valueIndex = valueIndexArray.join(';');
    }
    if (this.orgPath) {
      // tslint:disable-next-line:no-string-literal
      this.tagData["orgPath"] = this.orgPath;
    }
    if (this.tagData.formType === 'fileSelectWidget') {
      const valueIndexStr = this.getValueStrFromArray(this.tagData.valueIndexArray);
      this.tagData.valueN = valueIndexStr;
      const valueStr = this.getValueStrFromArray(this.tagData.valueArray);
      this.tagData.value = valueStr;
    }
    this.updateUrl.emit(this.tagData);
  }

  // web 上传文件
  uploadFile(event) {
    if (this.tagData.disabled && this.tagData.valueArray.length > 0) {
      this.pageModalService.openImage(0, this.tagData.valueArray);
      return;
    }

    this.uploadFileForWeb(event);
  }

  uploadFileForWeb(event: any, fileType?: string) {

    const that = this;
    if (event.target.files && event.target.files[0]) {
      this.selectImg = event.target.files[0];
      if (fileType && fileType === 'video') {
        if (this.selectImg.size > 1024 * 1024 * 200) {
          this.appGlobalService.showToast('视频不能大于200M，请重新选择', 3000, 'middle');
          return;
        }
      } else if (fileType && fileType === 'pdf') {

      } else {
        // if (this.selectImg.size > 1024 * 1024 * 5) {
        //   this.appGlobalService.showToast('图片不能大于5M，请重新选择', 3000, 'middle');
        //   return;
        // }
        if (this.tagData.allowCropper && this.maxSize === 1) {
          that.pageModalService.openImageToCropper({ url: URL.createObjectURL(this.selectImg), cropperRatio: this.tagData.cropperRatio },
            (res0) => {
              console.log("openImageToCropper:" + res0);
              if (res0) {
                const uploadData = new FormData();
                uploadData.append('file', res0, this.currentTime + ".png");
                this.showLoader();
                that.uploadImageWeb(uploadData);

              }
            });
          return;
        }
      }

      if (['jpeg', 'png', 'gif', 'jpg', 'mp4', 'pdf'].indexOf(this.selectImg.type.split('/')[1]) > -1) {

        const reader = new FileReader();
        reader.readAsDataURL(that.selectImg);
        reader.onload = (e) => {
          const uploadData = new FormData();
          uploadData.append('file', that.selectImg);
          if (fileType === 'video') {
            this.appGlobalService.totalFileUploadingNum = 0;
            let intervalId;
            if (intervalId) {
              clearInterval(intervalId); // 停止计时器
            }
            // 计时器，每秒钟改变一次 totalFileUploadingNum
            intervalId = setInterval(() => {
              // 获取当前值
              let currentValue = this.appGlobalService.totalFileUploadingNum;
              // 增加值，这里我们假设要增加到 0.5（或者100%的某个比例），
              // 你可以根据需要调整增加的逻辑，比如线性增加、非线性增加等。
              // 这里我们假设线性增加到 0.5
              const increment = 0.01; // 每秒增加 0.01，50 秒增加到 0.5
              currentValue += increment;

              // 如果达到或超过 0.5，则停止计时器
              if (currentValue >= 1) {
                currentValue = 1;
                clearInterval(intervalId); // 停止计时器
              }
              // 更新值
              this.appGlobalService.totalFileUploadingNum = currentValue;
              // 可以在这里添加其他逻辑，比如更新 UI 显示进度等
              console.log(`Progress: ${currentValue * 100}%`);
            }, 1000); // 每秒执行一次

            this.showLoader();
            that.http.img_post('file/uploadvideo', uploadData, res => {
              that.hideLoader();
              const result = res;
              console.log('video文件上传返回值.....');
              console.log(JSON.stringify(res));
              console.log('snapShot' + result.snapShot);
              console.log('videoUrl:' + result.videoUrl);
              that.tagData.subHtmlObj[1].value = result.videoUrl;
              that.tagData.subHtmlObj[1].size = that.selectImg.size;
              that.tagData.subHtmlObj[2].value = result.snapShot;
              that.updateUrl.emit(that.tagData);
            }, err => {
              that.hideLoader();
              that.appGlobalService.showToast('上传失败，请重试', 1500, 'middle');
            });
          } else if (fileType === 'pdf') {
            this.showLoader();
            that.http.img_post('file/uploadPdfToImage', uploadData, res => {
              that.hideLoader();
              const result = res;
              console.log('pdf文件上传返回值.....');
              console.log(JSON.stringify(res));
              console.log(res.url);
              console.log(res.indexThumbUrl);
              console.log(res.thumbUrl);

              if (that.tagData.valueArray.length === that.maxSize) {
                that.tagData.valueArray[that.maxSize - 1] = { path: res.url };
                that.tagData.valueLongArray[that.maxSize - 1] = { path: res.thumbUrl };
                that.tagData.valueIndexArray[that.maxSize - 1] = { path: res.indexThumbUrl };
              } else {
                that.tagData.valueArray.push({ path: res.url });
                that.tagData.valueLongArray.push({ path: res.thumbUrl });
                that.tagData.valueIndexArray.push({ path: res.indexThumbUrl });
              }

              that.updateTagData();
            }, err => {
              that.hideLoader();
              that.appGlobalService.showToast('上传失败，请重试', 1500, 'middle');
            });
          } else {

            that.uploadImageService.uploadFileForWeb(this.selectImg, (resUrl: any) => {

              if (that.tagData.valueArray.length === that.maxSize) {
                that.tagData.valueArray[that.maxSize - 1] = { path: resUrl };
              } else {
                that.tagData.valueArray.push({ path: resUrl });
              }
              that.updateTagData();
              // TODO: 是否有必要在弹出模态窗编辑
              if (that.tagData.formType === 'addReleasePhoto') {
                that.openImageModal();
              }
            }, that.tagData.cropperRatio);
          }

        };
      } else {
        if (fileType && fileType === 'video') {
          this.appGlobalService.showToast('格式不正确，请选择视频', 3000, 'middle');
        } else if (fileType && fileType === 'pdf') {
          this.appGlobalService.showToast('格式不正确，请选择pdf', 3000, 'middle');
        } else {
          this.appGlobalService.showToast('格式不正确，请选择图片', 3000, 'middle');
        }

      }
    }
  }
  uploadAllFileForWeb(event: any) {

    const that = this;
    if (event.target.files && event.target.files[0]) {
      this.selectImg = event.target.files[0];
      console.log('file type: ' + this.selectImg.type);
      if (this.selectImg.size > 1024 * 1024 * that.tagData.max) {
        this.appGlobalService.showToast('文件不能大于' + that.tagData.max + 'MB!', 2000, 'middle');
        return;
      }

      if (['jpeg', 'png', 'gif', 'jpg', 'mp4', 'pdf',
        'zip', 'vnd', 'rar'].indexOf(this.selectImg.type.split('/')[1]) > -1 || this.selectImg.type.split('/')[1].indexOf('vnd') > -1) {

        const reader = new FileReader();
        reader.readAsDataURL(that.selectImg);
        reader.onload = (e) => {
          const uploadData = new FormData();
          uploadData.append('file', that.selectImg);
          this.showLoader();
          that.http.img_post('file/uploadFile', uploadData, res => {
            that.hideLoader();
            console.log('文件上传返回值.....');
            console.log(JSON.stringify(res));
            if (that.tagData.valueArray.length === that.maxSize) {
              that.tagData.valueArray[that.maxSize - 1] = res.url;
              that.tagData.valueIndexArray[that.maxSize - 1] = that.selectImg.name;
              this.tagData.valueLongArray[that.maxSize - 1] = res.url.split('.').pop();
            } else {
              that.tagData.valueArray.push(res.url);
              this.tagData.valueLongArray.push(res.url.split('.').pop());
              that.tagData.valueIndexArray.push(that.selectImg.name);
            }

            that.updateUrl.emit(that.tagData);
          }, err => {
            that.hideLoader();
            that.appGlobalService.showToast('文件上传失败，请重试', 1500, 'middle');
          });
        };
      } else {
        that.appGlobalService.showToast('暂不支持该类型文件上传', 1500, 'middle');
      }

    }
  }
  uploadImageWeb(uploadData) {
    const that = this;
    let path = 'file/simpleUpload?waterMark=蜂喔';
    if (this.tagData.path && this.tagData.path.length > 0) {
      path = this.tagData.path;
    }
    if (that.tagData.orderItemId && that.tagData.orderItemId.length > 0) {
      uploadData.set('orderItemId', that.tagData.orderItemId);
    }
    that.http.img_post(path, uploadData, res => {
      that.hideLoader();
      let url = JSON.stringify(res.url).toString();
      console.log('message----->' + url);
      url = url.replace('"', '').replace('"', '');

      if (that.tagData.valueArray.length === that.maxSize) {
        that.tagData.valueArray[that.maxSize - 1] = { path: url };
      } else {
        that.tagData.valueArray.push({ path: url });
      }

      that.updateTagData();
      // TODO: 是否有必要在弹出模态窗编辑
      if (that.tagData.formType === 'addReleasePhoto') {
        that.openImageModal();
      }

    }, err => {
      that.appGlobalService.showToast('上传失败，请重试', 1500, 'middle');
      that.hideLoader();
    });
  }
  async presentVideoAction() {
    if (this.tagData.disabled) {
      return;
    }
    // 2024.12.02 初始化取消上传视频标志位
    this.isAbortUpload = false;

    // 2024.11.11 只有前端的上传文件才会触发此回调
    this.appGlobalService.uploadVideCompletedCallBack = (obj) => {
      this.compressionProgress = 0; // 取消之后清空
      this.uploadProgress = 0;
      this.appGlobalService.totalFileUploadingNum = 0;
      this.isAbortUpload = true;
      if (this.fileTransfer !== undefined) {
        this.fileTransfer.abort();
      }

      this.appGlobalService.showToast('文件上传已取消', 2000, 'top');
      this.pageModalService.closeModalWithId(this.uploadFileModalId); // 关闭弹窗
      return;
    };


    const actionSheet = await this.actionSheetCtrl.create({
      mode: 'ios',
      cssClass: 'as_padding as_common as_border_common',
      buttons: [{
        text: '相机',
        cssClass: 'as_font_bd',
        handler: () => {
          this.takeVideo();
        }
      }, {
        text: '从手机相册选择',
        cssClass: 'as_font_color',
        handler: () => {
          this.openVideoPicker();
          // this.appGlobalService.showToast('开发中...', 1500, 'top')
        }
      },
      {
        text: '取消',
        cssClass: 'as_font_top',
        handler: () => {
          console.log('Cancel clicked');
        }
      }]
    });
    await actionSheet.present();
  }

  // App 上传文件
  async presentAction(i) {
    const that = this;
    if (this.forPdf) {
      this.uploadFDF();
    } else {
      if (this.tagData.disabled && this.tagData.valueArray.length > 0) {
        this.pageModalService.openImage(0, this.tagData.valueArray);
        return;
      }
      if (this.tagData.valueArray.length >= this.maxSize && this.tagData.formType !== 'avatarSelectWidget') {
        this.appGlobalService.showToast('最多只能选择' + this.maxSize + '张', 1500, 'middle');
        return;
      }
      const actionSheet = await this.actionSheetCtrl.create({
        mode: 'ios',
        cssClass: 'as_padding as_common as_border_common',
        buttons: [{
          text: '相机',
          cssClass: 'as_font_bd',
          handler: () => {
            const source = this.camera.PictureSourceType.CAMERA;
            // 2024.06.14 整合统一从uploadImageService处理
            // tslint:disable-next-line:no-shadowed-variable
            this.uploadImageService.takePicture(source, that.tagData.allowEdit, (url) => {

              if (that.tagData.valueArray.length === that.maxSize) {
                that.tagData.valueArray[that.maxSize - 1] = { path: url };
              } else {
                that.tagData.valueArray.push({ path: url });
              }
              that.updateTagData();
              // TODO: 是否有必要在弹出模态窗编辑
              if (that.tagData.formType === 'addReleasePhoto') {
                that.openImageModal();
              }
            }, that.orgPath);
          }

        }, {
          text: '从手机相册选择',
          cssClass: 'as_font_color',
          handler: () => {

            // 2024.06.14 整合统一从uploadImageService处理

            this.uploadImageService.openImgPicker(
              // tslint:disable-next-line:no-shadowed-variable
              (url: any, fileName: any) => {
                that.hideLoader();
                if (that.tagData.valueArray.length === that.maxSize) {
                  that.tagData.valueArray[that.maxSize - 1] = { path: url };
                } else {
                  that.tagData.valueArray.push({ path: url });
                }

                that.updateTagData();
                // TODO: 是否有必要在弹出模态窗编辑
                if (that.tagData.formType === 'addReleasePhoto') {
                  that.openImageModal();
                }
              },
              that.maxSize,
              that.isCompleteBatchUpload,
              that.orgPath,
              that.tagData, this.ref);

          }
        },
        {
          text: '取消',
          cssClass: 'as_font_top',
          handler: () => {
            console.log('Cancel clicked');
          }
        }]
      });
      await actionSheet.present();
    }
  }

  openVideoPicker() {
    const args = {
      maxTime: 3600, // 需求变动 改为 3600 20220128
      selectMode: 102, // 101=picker image and video , 100=image , 102=video
      maxSelectCount: 1, // default 40 (Optional)
      maxSelectSize: 588743680, // 188743680=180M (Optional)
    };

    const that = this;      // 2024.05.28 安卓端新增判断
    MediaPicker.getMedias(args, async (medias) => {
      if (medias && medias.length > 0) {

        {
          // that.showLoaderWithMsg('视频上传中...');
          let limitFileSize = 10; // 可以配置文件大小 大于5MB时按配置的大小决定是否压缩
          if (this.tagData.min && Number(this.tagData.min) > 5) {
            limitFileSize = Number(this.tagData.min);
          }
          this.showFileUploadPopover('uploadFile', '');
          if (medias[0].size > 1024 * 1024 * limitFileSize) {

            that.transVideo(medias[0].uri);
          } else {
            // that.showLoaderWithMsg('视频上传中...');
            that.uploadVideo(medias[0].uri, that.getFileName(medias[0].uri), medias[0].size, '0');
          }
        }
      }

    }, (err) => {
      console.log(' error-----> take video from album ' + JSON.stringify(err));
      if (err === 'show setting') {
        that.pageModalService.showSettingAlbum();
      }
    });
  }

  getFileName(path) {
    const pos1 = path.lastIndexOf('/');
    const pos2 = path.lastIndexOf('\\');
    const pos = Math.max(pos1, pos2);
    if (pos < 0) {
      return path;
    } else {
      return path.substring(pos + 1);
    }
  }

  takeVideo() {
    console.log(' message----->  begin takeVideo ');
    const options: VideoCapturePlusOptions = {
      limit: 1,
      duration: 3600,  // 需求变动 改为 3600 20220128
      highquality: true,
      // portraitOverlay: 'assets/img/camera/overlay/portrait.png',
      // landscapeOverlay: 'assets/img/camera/overlay/landscape.png'
    };
    const that = this;

    this.videoCapturePlus.captureVideo(options).then((mediafile: MediaFile[]) => {
      // console.log(mediafile);
      const videoFile = mediafile[0];
      let limitFileSize = 10; // 可以配置文件大小 大于5MB时按配置的大小决定是否压缩
      if (this.tagData.min && Number(this.tagData.min) > 5) {
        limitFileSize = Number(this.tagData.min);
      }
      this.showFileUploadPopover('uploadFile', '');
      if (videoFile.size > 1024 * 1024 * limitFileSize) {
        that.transVideo(videoFile.fullPath);
      } else {
        // that.showLoaderWithMsg('视频上传中...');
        that.uploadVideo(videoFile.fullPath, that.getFileName(videoFile.fullPath), videoFile.size, '0');
      }
      // this.transVideo(videoFile.fullPath);
    }, error => {
      console.log('videoCapturePlus Something went wrong');
      console.log(' error-----> take video with camera ' + JSON.stringify(error));
      if (error === 'show setting') {
        that.pageModalService.showSettingVideo();
      }
    });

  }

  async transVideo(fullPath) {
    this.compressionProgress = 0;
    this.isAbortUpload = false; // 初始化取消标志位 2024.11.11 用户主动取消上传文件
    console.log('Transcode Video start');
    const outFileName = (new Date()).valueOf();
    console.log(outFileName);
    // this.showLoaderWithMsg('视频上传中...');
    this.videoEditor.getVideoInfo({ fileUri: fullPath }).then(res2 => {
      // if (timer) { clearInterval(timer); loading.dismiss(); }
      this.appGlobalService.consoleLog('压缩前的大小：', res2.size / 1024 / 1024 + '兆');
      this.appGlobalService.consoleLog('压缩前的宽度：', res2.width);
      this.appGlobalService.consoleLog('压缩前的高度：', res2.height);
      const width = res2.width;
      const height = res2.height;
      const minDimension = Math.min(width, height);
      // 2k  2460 x 1440
      // 4k  3960 x 2560
      // 大于最小压缩值就压缩 设置为1080像素
      let limitSize = 1080;
      if (this.tagData.max && Number(this.tagData.max) > 540) {
        limitSize = Number(this.tagData.max);
      }
      let newWidth = 0;
      let newHeight = 0;
      if (minDimension > limitSize) {
        const scaleFactor = limitSize / minDimension; // 缩小比例
        newWidth = Math.round(width * scaleFactor);
        newHeight = Math.round(height * scaleFactor);
      } else {
        newWidth = width;
        newHeight = height;
      }
      this.videoEditor.transcodeVideo({
        fileUri: fullPath,
        outputFileName: outFileName + '',
        outputFileType: this.videoEditor.OutputFileType.MPEG4,
        saveToLibrary: false,
        // optimizeForNetworkUse: 30,
        width: newWidth,
        height: newHeight,
        progress: (info: any) => {
          if (this.isAbortUpload) {
            // this.videoEditor.abort();
            this.compressionProgress = 0;
            this.appGlobalService.totalFileUploadingNum = 0;
            this.videoEditor.createThumbnail({ fileUri: '', outputFileName: '' });
            return;
          }
          // const num = Math.ceil(info);
          this.compressionProgress = info * 0.5;
          this.updateTotalProgress();
          console.log('Transcode Video progress:' + info);
        }
      }).then((fileUri: string) => {
        if (this.isAbortUpload) {
          return;
        }
        console.log('video transcode success', fileUri);
        this.videoEditor.getVideoInfo({ fileUri }).then(res => {
          this.appGlobalService.consoleLog('压缩后的大小：', res.size / 1024 / 1024 + 'MB');
          this.appGlobalService.consoleLog('压缩后的宽度：', res.width);
          this.appGlobalService.consoleLog('压缩后的高度：', res.height);
          if (res && res.size) {
            this.uploadVideo(fileUri, outFileName, res.size, '1');
          } else {
            this.uploadVideo(fileUri, outFileName, 0, '1');
          }
        });
      })
        .catch((error: any) => {
          console.log('video transcode error', error);
          this.hideLoader();

        });

    });
  }
  uploadVideo(fileUrl, outFileName, size, isCompressed?) {
    this.fileTransfer = this.transfer.create();
    const options: FileUploadOptions = {
      fileKey: 'file',
      fileName: outFileName + '.mp4',
      mimeType: "video/mp4",
      httpMethod: 'POST',
      params: { timeout: 150000 }, // 150秒
      // headers: {'Content-Type': 'multipart/form-data'}
    };
    const that = this;
    const url = this.http.bathUrl + 'file/uploadvideo';
    let progressValue = 0;

    // 正在上传中...
    this.fileTransfer.onProgress((progressEvent) => {

      if (this.isAbortUpload) {
        return;
      }

      if (progressEvent.lengthComputable) {
        // Calculate the percentage
        //  0.4391339173755058
        progressValue = progressEvent.loaded / progressEvent.total;

        if (isCompressed === '1') {
          this.uploadProgress = progressValue * 50;
        } else {
          this.uploadProgress = progressValue * 100;
        }
        this.updateTotalProgress();
        this.appGlobalService.consoleLog('上传进度...1', progressValue);
      }
    });


    if (this.isAbortUpload) {
      this.appGlobalService.consoleLog('fileTransfer upload Video cancelled', '  	   ');
      return;
    }

    this.fileTransfer.upload(fileUrl, encodeURI(url), options).then((res) => {
      const result = JSON.parse(res.response);
      this.appGlobalService.totalFileUploadingNum = 1;
      this.pageModalService.closeModalWithId(this.uploadFileModalId); // 关闭弹窗
      console.log('文件上传返回值.....');
      console.log(JSON.stringify(res));
      console.log('snapShot' + result.snapShot);
      console.log('videoUrl:' + result.videoUrl);

      this.tagData.subHtmlObj[1].value = result.videoUrl;
      this.tagData.subHtmlObj[1].size = size;
      this.tagData.subHtmlObj[2].value = result.snapShot;
      this.updateUrl.emit(this.tagData);
      this.hideLoader();
      setTimeout(() => {
        // 2024.11.01  上传完成刷新值
        this.compressionProgress = 0;
        this.uploadProgress = 0;
        this.appGlobalService.totalFileUploadingNum = 0;
      }, 500);


    }).catch((error: any) => {
      console.log(' uploadvideo error', error);
      this.hideLoader();
    });



  }


  // 更新上传总进度
  updateTotalProgress() {
    const totalUploadNum = (this.compressionProgress + this.uploadProgress) / 100;
    this.appGlobalService.consoleLog('this.compressionProgress =', this.compressionProgress);
    this.appGlobalService.consoleLog('this.uploadProgress =', this.uploadProgress);
    this.appGlobalService.totalFileUploadingNum = totalUploadNum === 1 ? 0.99 : totalUploadNum;
    this.appGlobalService.consoleLog('上传文件总进度：', this.appGlobalService.totalFileUploadingNum);
  }


  showLoaderWithMsg(msg?) {
    this.loaderToShow = this.loadingController.create({
      message: msg ? msg : '上传文件中...'
    }).then((res) => {
      res.present();
      res.onDidDismiss().then((dis) => {
        this.ref.detectChanges(); // trigger change detection cycle
      });
    });
  }

  playVideo(e) {
    e.stopPropagation();
    console.log('paly');
  }
  delVideo(e) {
    e.stopPropagation();
    console.log('del');
    this.tagData.subHtmlObj[1].value = '';
    this.tagData.subHtmlObj[2].value = '';
    this.updateUrl.emit(this.tagData);
  }
  delImg(e, item) {
    e.stopPropagation();
    console.log('del');

    if (this.forPdf) {
      const index = this.tagData.valueIndexArray.indexOf(item);
      this.tagData.valueArray.splice(index, 1);
      this.tagData.valueIndexArray.splice(index, 1);
      this.tagData.valueLongArray.splice(index, 1);
    } else {
      const index = this.tagData.valueArray.indexOf(item);
      this.tagData.valueArray.splice(index, 1);
    }
    this.updateTagData();
  }
  showLoader() {
    this.loaderToShow = this.loadingController.create({
      message: '上传文件中...'
    }).then((res) => {
      res.present();
      res.onDidDismiss().then((dis) => {
        this.ref.detectChanges(); // trigger change detection cycle
      });
    });
  }

  hideLoader() {
    const that = this;
    setTimeout(() => {
      if (that.loadingController) {
        that.loadingController.dismiss();
      }
    }, 1000);
  }

  // 打开图片展示框，滑动展示
  async choosePhoto(pos) {
    if (this.tagData.disabled && this.tagData.valueArray.length > 0) {
      this.pageModalService.openImage(0, this.tagData.valueArray);
      return;
    }
    const that = this;
    let componentProps = {};
    if (this.forPdf) {
      componentProps = { value: JSON.stringify(this.tagData), index: pos, forPdf: true };
    } else {
      componentProps = { value: JSON.stringify(this.tagData.valueArray), index: pos, forPdf: false };
    }
    const modal = await this.modalCtrl.create({
      component: ImgPage,
      componentProps
    });
    modal.onDidDismiss().then((data) => {
      if (that.forPdf) {
        that.tagData.valueIndexArray = data.data.valueIndexArray;
        that.tagData.valueLongArray = data.data.valueLongArray;
        that.tagData.valueArray = data.data.valueArray;
      } else {
        that.tagData.valueArray = data.data;
      }

      that.updateTagData();
    });
    return await modal.present();
  }

  async openImageModal(e?) {
    if (e) {
      e.stopPropagation();
    }
    const that = this;
    const modal = await this.modalCtrl.create({
      component: UploadImageComponent,
      componentProps: { value: JSON.stringify(this.tagData.valueArray), imgCount: this.maxSize }
    });
    modal.onDidDismiss().then((data) => {
      if (data.data) {
        that.tagData.valueArray = data.data;
      }
      that.updateTagData();

    });
    return await modal.present();
  }

  getBackground(image) {
    return this.sanitizer.bypassSecurityTrustStyle(`url(${image})`);
  }
  showSetting(err) {
    if (err === 'show setting') {
      this.pageModalService.showSettingAlbum();
    }
  }

  // pdf文件上传 android and ios
  //  * @param accept Optional MIME type filter (e.g. 'image/gif,video/*').
  //  chooser.getFile(accept?: string) : Promise<undefined|{
  // 	data: Uint8Array;
  // 	dataURI: string;
  // 	mediaType: string;
  // 	name: string;
  // 	uri: string;
  // }
  uploadFDF() {
    const that = this;
    this.chooser.getFile('application/pdf')
      .then(file => {

        if (localStorage.getItem('platform') === 'ios') {
          that.uploadFileByPath(file.uri, file.name);
        } else {
          that.uploadFDFAndroid(file.data, file.name, file.mediaType);
        }


      })
      .catch((error: any) => console.error(error));
  }
  // Ap p
  uploadAllFile() {
    const that = this;
    this.chooser.getFile()
      .then(file => {
        // 此处会引起安卓上传不了
        // console.log(file ? file.name : 'canceled');
        // console.log(file ? JSON.stringify(file) : 'canceled');


        if (localStorage.getItem('platform') === 'ios') {
          that.uploadAllFileByPath(file.uri, file.name);
        } else {
          that.uploadALlFileAndroid(file.data, file.name, file.mediaType);
        }


      })
      .catch((error: any) => console.error(error));
  }
  // pdf文件上传 only Android
  uploadFDFAndroid(blobData, fileName, fileType) {
    const uploadData = new FormData();
    const pdfBlob = new Blob([blobData], {
      type: fileType
    });
    uploadData.append('file', pdfBlob, fileName);
    const that = this;
    this.http.img_post('file/uploadPdfToImage', uploadData, res => {
      this.hideLoader();
      // const res = JSON.parse(data.response);
      console.log(res + '这里就可以做回显或者其他操作了');
      console.log(res.url);
      console.log(res.indexThumbUrl);
      console.log(res.thumbUrl);

      if (that.tagData.valueArray.length === that.maxSize) {
        that.tagData.valueArray[that.maxSize - 1] = { path: res.url };
        that.tagData.valueLongArray[that.maxSize - 1] = { path: res.thumbUrl };
        that.tagData.valueIndexArray[that.maxSize - 1] = { path: res.indexThumbUrl };
      } else {
        that.tagData.valueArray.push({ path: res.url });
        that.tagData.valueLongArray.push({ path: res.thumbUrl });
        that.tagData.valueIndexArray.push({ path: res.indexThumbUrl });
      }
      that.updateTagData();
    }, err => {
      this.hideLoader();
      this.appGlobalService.showToast('上传失败，请重试', 1500, 'middle');
    });
  }



  uploadFileByPath(filepath, fileName?) {
    this.showLoader();
    const that = this;
    const fileTransfer: FileTransferObject = this.transfer.create();
    // 该配置项options详情见 https://github.com/apache/cordova-plugin-file-transfer
    const options: FileUploadOptions = {
      fileKey: 'file',
      fileName: fileName ? fileName : ((new Date()).valueOf() + filepath.substring(filepath.lastIndexOf(".") + 1, filepath.length)),
      headers: {},
    };

    fileTransfer.upload(filepath, encodeURI(this.http.bathUrl + 'file/uploadPdfToImage'), options)
      .then((data: any) => {
        that.hideLoader();
        const res = JSON.parse(data.response);
        console.log(res + '这里就可以做回显或者其他操作了');
        console.log(res.url);
        console.log(res.indexThumbUrl);
        console.log(res.thumbUrl);

        if (that.tagData.valueArray.length === that.maxSize) {
          that.tagData.valueArray[that.maxSize - 1] = { path: res.url };
          that.tagData.valueLongArray[that.maxSize - 1] = { path: res.thumbUrl };
          that.tagData.valueIndexArray[that.maxSize - 1] = { path: res.indexThumbUrl };
        } else {
          that.tagData.valueArray.push({ path: res.url });
          that.tagData.valueLongArray.push({ path: res.thumbUrl });
          that.tagData.valueIndexArray.push({ path: res.indexThumbUrl });
        }

        that.updateTagData();
        // success
      }, (err) => {
        // error
        console.log('失败');
        that.hideLoader();
        that.appGlobalService.showToast('文件上传失败！', 1500, "top");
      });

  }
  // 文件上传 only Android
  uploadALlFileAndroid(blobData, fileName, fileType) {
    const uploadData = new FormData();
    const pdfBlob = new Blob([blobData], {
      type: fileType
    });
    uploadData.append('file', pdfBlob, fileName);
    const that = this;
    this.http.img_post('file/uploadFile', uploadData, res => {
      this.hideLoader();
      // const res = JSON.parse(data.response);
      console.log(res + '这里就可以做回显或者其他操作了');
      console.log(res.url);
      console.log(res.indexThumbUrl);
      console.log(res.thumbUrl);
      if (that.tagData.valueArray.length === that.maxSize) {
        that.tagData.valueArray[that.maxSize - 1] = res.url;
        that.tagData.valueIndexArray[that.maxSize - 1] = that.selectImg.name;
        this.tagData.valueLongArray[that.maxSize - 1] = res.url.split('.').pop();
      } else {
        that.tagData.valueArray.push(res.url);
        this.tagData.valueLongArray.push(res.url.split('.').pop());
        that.tagData.valueIndexArray.push(that.selectImg.name);
      }
      that.updateUrl.emit(that.tagData);

    }, err => {
      this.hideLoader();
      this.appGlobalService.showToast('上传失败，请重试', 1500, 'middle');
    });
  }
  uploadAllFileByPath(filepath, fileName?) {
    this.showLoader();
    const that = this;
    const fileTransfer: FileTransferObject = this.transfer.create();
    // 该配置项options详情见 https://github.com/apache/cordova-plugin-file-transfer
    const options: FileUploadOptions = {
      fileKey: 'file',
      fileName: fileName ? fileName : ((new Date()).valueOf() + filepath.substring(filepath.lastIndexOf(".") + 1, filepath.length)),
      headers: {},
    };

    fileTransfer.upload(filepath, encodeURI(this.http.bathUrl + 'file/uploadFile'), options)
      .then((data: any) => {
        that.hideLoader();
        const res = JSON.parse(data.response);
        console.log(res + '这里就可以做回显或者其他操作了');
        console.log(res.url);
        console.log(res.indexThumbUrl);
        console.log(res.thumbUrl);
        that.tagData.value = res.url;
        that.tagData.valueN = that.selectImg.name;
        that.updateUrl.emit(that.tagData);
        // success
      }, (err) => {
        // error
        console.log('失败');
        that.hideLoader();
        that.appGlobalService.showToast('文件上传失败！', 1500, "top");
      });

  }
  textClick(event) {
    event.stopPropagation();
  }
  changeValue(event, i) {

    this.updateTagData();
  }

  errorCheckedForPhotoVideoWidget() {
    if (this.appGlobalService.formChecked) {
      if (this.checkItemError(this.tagData.subHtmlObj[0])) {
        return this.tagData.subHtmlObj[0].placeHolder;
      } else
        if (this.checkItemError(this.tagData.subHtmlObj[1])) {
          return this.tagData.subHtmlObj[1].placeHolder;
        } else
          if (this.checkItemError(this.tagData.subHtmlObj[2])) {
            return this.tagData.subHtmlObj[2].placeHolder;
          } else {
            return false;
          }
    } else {
      return false;
    }
  }
  checkItemError(item) {
    if (item.required && item.showErrorStyle && item.placeHolder &&
      (!item.value || item.value === '')) {
      return item.placeHolder;
    } else {
      return false;
    }
  }

  delFile(e, item) {
    e.stopPropagation();
    console.log('del');
    const index = this.tagData.valueArray.indexOf(item);
    this.tagData.valueArray.splice(index, 1);
    this.tagData.valueIndexArray.splice(index, 1);
    this.tagData.valueLongArray.splice(index, 1);

    this.updateTagData();
  }
  downloadFile() {
    if (this.tagData.value !== "") {
      this.pageModalService.openPage({ type: "url", params: { download: 'true' }, target: this.tagData.value });
    }
  }
}
